package org.wicket.jbpm.task.panel;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.ajax.markup.html.IndicatingAjaxButton;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.wicket.jbpm.engine.spring.JbpmCoreEngine;

/**
 * @author Emmanuel Nollase - emanux
 * created: Jun 23, 2009 - 6:01:19 PM
 */
public abstract class TransitionButtonPanel extends Panel {

	
	public TransitionButtonPanel(final String id,final Form form,final boolean hasComments,final boolean hasVariables,
								 final JbpmCoreEngine jbpmEngine) {
		super(id);
		
		final String pathId = getPathId();
		final String taskInstId = getTaskInstId();
		
		final List<String> transitions = jbpmEngine.getTaskLeavingTransition(taskInstId);
		
		final ListView listTrans = new ListView("transitions", transitions){
			@Override
			protected void populateItem(ListItem item) {
				final String buttLabel = item.getDefaultModelObjectAsString();
				final IndicatingAjaxButton transbut = new IndicatingAjaxButton("transbutt", form){
					@Override
					protected void onSubmit(AjaxRequestTarget target, Form form) {
						Map<String, Serializable> param = null;
						String comment = null;
						if(hasVariables) 
						{
							param = getParameters(form);
						}
						if(hasComments)
						{
							comment = getComments(form);
						}
						
						jbpmEngine.signalTask(pathId, buttLabel);
						jbpmEngine.endTask(taskInstId, comment, param);
					}
				};
				transbut.add(new Label("label", StringUtils.isNotBlank(buttLabel) ? buttLabel : "Submit"));
				item.add(transbut);
			}
		};
		add(listTrans);
	}

	private Map<String,Serializable> getParameters(Form form)
	{
		final Map<String, Serializable> params = new HashMap<String, Serializable>();
		//final LoanApp loanapp = (LoanApp) form.getModelObject();
		// TODO add here the parameter to be used from loan application
		// params.put("","");
		
		return params;
	}
	
	private String getComments(Form form)
	{
		//final LoanApp loanapp = (LoanApp) form.getModelObject();
		// retreive comments source ???????????
		
		return null;
	}
	
	public abstract String getPathId();
	
	public abstract String getTaskInstId();
}

